/**
 * Copyright (c) 2004-2015 All Rights Reserved.
 */
package com.zbest.zpay.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.zbest.common.lang.enums.BizCode;
import com.zbest.common.lang.util.JSONUtil;
import com.zbest.zpay.service.apiserver.model.ApiServerKeyEnum;

/**
 * 
 *
 * @author czhou3306@gmail.com
 * @version $Id: LoginFilter.java, v0.1 2015年12月7日 下午4:47:34 czhou3306@gmail.com Exp $
 */
public class LoginFilter implements Filter, InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    private String              userKey;

    private List<String>        excludeUrl;

    private List<Pattern>       patternList;

    /** 
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /** 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                                                                                             throws IOException,
                                                                                             ServletException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            String requestUrl = httpServletRequest.getRequestURI();
            boolean checkSession = true;
            //FIXME modify 正则
            /*for (Pattern pattern : patternList) {
                if (pattern.matcher(requestUrl).matches()) {
                    checkSession = false;
                    break;
                }
            }*/

            for (String url : excludeUrl) {
                if (requestUrl.contains(url)) {
                    checkSession = false;
                    break;
                }
            }

            if (!checkSession) {
                chain.doFilter(httpServletRequest, response);
            } else {
                if (httpServletRequest.getSession().getAttribute(userKey) != null) {
                    chain.doFilter(httpServletRequest, response);
                } else {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put(ApiServerKeyEnum.KEY_CODE.getCode(), BizCode.USER_NOT_LOGIN.code());
                    map.put(ApiServerKeyEnum.KEY_MSG.getDesc(), BizCode.USER_NOT_LOGIN.desc());
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(JSONUtil.toJson(map));
                }
            }
        } catch (Exception e) {
            logger.error("处理http请求时异常", e);

            Map<String, Object> map = new HashMap<String, Object>();
            map.put(ApiServerKeyEnum.KEY_CODE.getCode(), BizCode.UNKNOWN.code());
            map.put(ApiServerKeyEnum.KEY_MSG.getCode(), BizCode.UNKNOWN.desc());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONUtil.toJson(map));

        }

    }

    /** 
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy() {
    }

    /** 
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        patternList = new ArrayList<Pattern>();
        for (String url : excludeUrl) {
            Pattern patter = Pattern.compile(url);
            patternList.add(patter);
        }
    }

    /**
     * Setter method for property <tt>userKey</tt>.
     * 
     * @param userKey value to be assigned to property userKey
     */
    public void setUserKey(String userKey) {
        this.userKey = userKey;
    }

    /**
     * Setter method for property <tt>excludeUrl</tt>.
     * 
     * @param excludeUrl value to be assigned to property excludeUrl
     */
    public void setExcludeUrl(List<String> excludeUrl) {
        this.excludeUrl = excludeUrl;
    }

}
